package com.example.temp.controller;

import com.example.temp.entity.ClassEntity;
import com.example.temp.common.Result;
import com.example.temp.entity.Student;
import com.example.temp.mapper.ClassMapper;
import com.example.temp.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/class")
@Slf4j
public class ClassController {

    @Autowired
    private ClassMapper classMapper;
    
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 添加班级
    @PostMapping("/insert")
    public Result insertClass(@RequestBody ClassEntity class1, @RequestParam(required = false) Integer role, @RequestParam(required = false) String teacherId) {
        try {
            log.info("添加班级: {}", class1);
            log.info("角色: {}", role);
            log.info("教师ID: {}", teacherId);
            // 如果是教师角色，验证教师ID
            if (role != null && role == 1 && teacherId != null) {
                // 验证教师只能添加自己为班主任的班级
                if (!teacherId.equals(class1.getTeacherID())) {
                    return Result.fail("教师只能添加自己为班主任的班级");
                }
            }
            
            int result = classMapper.insert(class1);
            if (result > 0) {
                return Result.success("班级添加成功");
            } else {
                return Result.fail("班级添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("班级添加出错：" + e.getMessage());
        }
    }

    // 获取班级名称
    @GetMapping("/acquireName")
    public Result acquireName(){
        List<String> classNameList = classMapper.acquireName();
        return Result.success(classNameList);
    }

    // 查询班级
    @GetMapping("/queryClass")
    public Result queryClass(@RequestParam String className) {
        ClassEntity classEntity = classMapper.queryClass(className);
        return Result.success(classEntity);
    }

    // 修改班级信息
    @PutMapping("/update")
    public Result updateClass(@RequestBody ClassEntity class1, @RequestParam(required = false) Integer role, @RequestParam(required = false) String teacherId) {
        try {
            // 获取当前班级信息以进行校验
            ClassEntity existingClass = classMapper.findById(class1.getClassId());
            if (existingClass == null) {
                return Result.fail("班级不存在");
            }
            
            // 如果是教师角色，验证权限
            if (role != null && role == 1 && teacherId != null) {
                // 验证教师是否为该班的班主任
                if (!teacherId.equals(existingClass.getTeacherID())) {
                    return Result.fail("您不是该班级的班主任，无法修改");
                }
                
                // 验证教师是否试图修改班主任
                if (!class1.getTeacherID().equals(existingClass.getTeacherID())) {
                    return Result.fail("教师不能修改班级的班主任");
                }
            }
            
            // 执行更新操作
            int result = classMapper.update(class1);
            if (result > 0) {
                return Result.success("班级信息更新成功");
            } else {
                return Result.fail("班级信息更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("班级信息更新出错：" + e.getMessage());
        }
    }

    // 分页查询班级
    @GetMapping("/showPage")
    public Result showPageClass(@RequestParam String query, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        List<ClassEntity> classes;
        int total;
        Map<String, Object> params = new HashMap<>();
        params.put("query", query);
        params.put("pageNum", (pageNum - 1) * pageSize);
        params.put("pageSize", pageSize);
        classes = classMapper.search(params);
        total = classMapper.getTotal(query);
        return Result.success(total, classes);
    }

    // 删除班级
    @DeleteMapping()
    public Result deleteClass(@RequestParam("className") String className) {
        int result = classMapper.delete(className);
        return Result.success(result);
    }
    
    // 获取所有班级(管理员访问)
    @GetMapping("/findAll")
    public Result findAllClasses() {
        List<ClassEntity> classes = classMapper.findAll();
        return Result.success(classes);
    }
    
    // 教师查询自己负责的班级
    @GetMapping("/findByTeacher")
    public Result findClassesByTeacher(@RequestParam String teacherId) {
        try {
            List<ClassEntity> classes = classMapper.findByTeacherId(teacherId);
            return Result.success(classes);
        } catch (Exception e) {
            return Result.fail("查询班级失败: " + e.getMessage());
        }
    }
    
    // 教师根据班级名称查询自己负责的班级
    @GetMapping("/findByTeacherAndName")
    public Result findClassesByTeacherAndName(@RequestParam String teacherId, @RequestParam String className) {
        try {
            List<ClassEntity> allTeacherClasses = classMapper.findByTeacherId(teacherId);
            
            List<ClassEntity> filteredClasses = new ArrayList<>();
            for (ClassEntity cls : allTeacherClasses) {
                if (cls.getClassName().contains(className)) {
                    filteredClasses.add(cls);
                }
            }
            
            return Result.success(filteredClasses);
        } catch (Exception e) {
            return Result.fail("查询班级失败: " + e.getMessage());
        }
    }
    
    // 获取班级详细信息
    @GetMapping("/info/{classId}")
    public Result getClassInfo(@PathVariable Integer classId) {
        try {
            ClassEntity classEntity = classMapper.findById(classId);
            if (classEntity == null) {
                return Result.fail("班级不存在");
            }
            return Result.success(classEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取班级信息失败: " + e.getMessage());
        }
    }
    
    // 学生查询自己所属的班级
    @GetMapping("/findByStudent")
    public Result findClassByStudent(@RequestParam String studentId) {
        Student student = studentMapper.findByID(studentId);
        if (student == null) {
            return Result.fail("学生信息不存在");
        }
        
        String className = student.getClassName();
        ClassEntity classEntity = classMapper.queryClass(className);
        return Result.success(classEntity);
    }
    
    // 根据班级名称获取班级信息
    @GetMapping("/getByName")
    public Result getByName(@RequestParam String className) {
        try {
            ClassEntity classEntity = classMapper.queryClass(className);
            if (classEntity == null) {
                return Result.fail("班级不存在");
            }
            return Result.success(classEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取班级信息失败：" + e.getMessage());
        }
    }
    
    // 获取班级学生列表
    @GetMapping("/students")
    public Result getClassStudents(
        @RequestParam Integer classId,
        @RequestParam(required = false) String query,
        @RequestParam(required = false, defaultValue = "1") Integer pageNum,
        @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        
        try {
            // 验证班级是否存在
            ClassEntity classEntity = classMapper.findById(classId);
            if (classEntity == null) {
                return Result.fail("班级不存在");
            }
            
            // 获取该班级的学生列表
            List<Student> students = studentMapper.findByClassId(classId);
            if (students == null) {
                students = new ArrayList<>();
            }
            
            // 处理查询参数（如果有）
            if (query != null && !query.trim().isEmpty()) {
                final String searchQuery = query.trim().toLowerCase();
                // 过滤学生列表
                students = students.stream()
                    .filter(s -> {
                        boolean matchesId = (s.getStudentID() != null && s.getStudentID().toLowerCase().contains(searchQuery));
                        boolean matchesName = (s.getName() != null && s.getName().toLowerCase().contains(searchQuery));
                        return matchesId || matchesName;
                    })
                    .collect(Collectors.toList());
            }
            
            // 计算总记录数
            int total = students.size();
            
            // 分页处理
            int start = (pageNum - 1) * pageSize;
            int end = Math.min(start + pageSize, total);
            
            // 获取当前页的数据
            List<Student> pageStudents = new ArrayList<>();
            if (start < total) {
                pageStudents = students.subList(start, end);
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("list", pageStudents);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取班级学生列表失败：" + e.getMessage());
        }
    }
}
